package com.zhou.util.img;

import cn.hutool.core.codec.Base64;
import lombok.Data;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;

/**
 * @author lang.zhou
 * @date 2022/5/25 15:20
 */
@Data
public class Base64Image {
    //
    private String fullString;
    //xxxxxx
    private String dataString;
    private byte[] data;
    //data:image/jpeg;base64,
    private String head;
    //文件后缀
    private String prefix;

    public Base64Image(String fullString) {
        this.fullString = fullString;
        this.dataString = fullString.substring(fullString.indexOf(",", 1) + 1);
        this.head = fullString.substring(0 , fullString.indexOf(",", 1)+1);
        int index = head.indexOf(";base64,");
        this.prefix = head.substring(head.indexOf("/")+1,index);
        this.data = Base64.decode(this.dataString);
    }
    public Base64Image(byte[] data,String prefix) {
        this.prefix = prefix;
        this.head = "data:image/"+prefix+";base64,";
        this.data = data;
        this.dataString = Base64.encode(data);
        this.fullString = this.head + this.dataString;
    }
    public ByteArrayInputStream toStream(){
        return new ByteArrayInputStream(data);
    }
    public void write(String file) throws Exception{
        FileUtils.writeByteArrayToFile(new File(file),this.data);
    }
    public void write(File file) throws Exception{
        FileUtils.writeByteArrayToFile(file,this.data);
    }
}
